﻿package  {
	import flash.geom.Point;
	
	public class Pawn extends Piece 
	{
		public var pieceName:String = "pawn";

		public function Pawn(pieceColor:String, currentRow:int, currentColumn:int, firstMove:Boolean=false)
		{
			this.firstMove = firstMove;
			super(pieceColor, currentRow, currentColumn);
		}
		
		public function moves(board:Array, enPassantPawn:Object):Array
		{
			positions = new Array();
			currentBoard = board;
			var verticalSteps:int = 1;
			var diagonalStep:int = 1;
			
			if(this.firstMove) {
				verticalSteps = 2;
			}
			
			var leftPassant:Boolean = false;
			var rightPassant:Boolean = false;
			
			if (enPassantPawn != null && enPassantPawn.pieceColor != this.pieceColor)
			{
				if (this.row == enPassantPawn.row && (this.column - 1) == enPassantPawn.column)
					leftPassant = true;
				else if (this.row == enPassantPawn.row && (this.column + 1) == enPassantPawn.column)
					rightPassant = true;
			}
			
			if(this.pieceColor == 'white')
			{
				up(verticalSteps);
				attack(-diagonalStep);
				
				if (leftPassant && currentBoard[this.row - 1][this.column - 1] == null)
					positions.push( new Point(this.row - 1, this.column - 1) );
				else if (rightPassant && currentBoard[this.row - 1][this.column + 1] == null)
					positions.push( new Point(this.row - 1, this.column + 1) );
			}
			else
			{
				down(verticalSteps);
				attack(diagonalStep);
				
				if (leftPassant && currentBoard[this.row + 1][this.column - 1] == null)
					positions.push( new Point(this.row + 1, this.column - 1) );
				else if (rightPassant && currentBoard[this.row + 1][this.column + 1] == null)
					positions.push( new Point(this.row + 1, this.column + 1) );
			}
			
			return positions;
		}
		
		override public function down(steps:int):void
		{
			for(var i:int = (this.row + 1); i <= (this.row + steps); i++)
			{
				if(currentBoard[i][this.column] != null || i > 7)
					break;
				else
				{
					positions.push( new Point(i,this.column));
				}
			}
		}
		
		override public function up(steps:int):void
		{
			for(var i:int = (this.row - 1); i >= (this.row - steps); i--)
			{
				if(currentBoard[i][this.column] != null || i < 0)
					break;
				else
				{
					positions.push( new Point(i,this.column));
				}
			}
		}
		
		public function attack(steps:int):void
		{	
			var attackRow:int = this.row + steps;
			
			if(attackRow > 7 || attackRow < 0)
				return;
			
			for(var j:int = (this.column - 1); j <= (this.column + 1); j++)
			{
				if(j == this.column || j < 0 || j > 7)
						continue;
						
				if(currentBoard[attackRow][j] != null)
				{
					if (this.pieceColor != currentBoard[attackRow][j].pieceColor) 
					{
						positions.push( new Point(attackRow,j));
					}
				}
			}
		}

	}
	
}
